import React, {useEffect, useState} from "react";
import {Button, Cascader, CascaderProps, Col, DatePicker, Form, Input, message, Modal, Row, Select} from "antd";
import type {Result} from "@/types/result";
import employeeApi from "@/api/employeeApi.ts";
import {Employee} from "@/types/resp/employee";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import DepartmentSelector from "@/pages/department/DepartmentSelector.tsx";
import PositionSelector from "@/pages/position/PositionSelector.tsx";
import {AreaOption} from "@/types/areaOption.ts";
import areas from "@/locales/area.json";

interface EmployeeAddProps {
  visible: boolean;
  id: number;
  onCloseEmployeeAdd: () => void;
}

const EmployeeAdd: React.FC<EmployeeAddProps> = ({visible, id, onCloseEmployeeAdd}) => {

  const [form] = Form.useForm<Employee>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    enterpriseName: [
      { required: true, message: '请输入企业名称' }
    ],
    employeeNumber: [
      { required: true, message: '请输入工号' }
    ],
    name: [
      { required: true, message: '请输入姓名' }
    ],
    password: [
      { required: true, message: '请输入密码' }
    ],
    gender: [
      { required: true, message: '请输入性别' }
    ],
    birthDate: [
      { required: true, message: '请输入出生日期' }
    ],
    contactPhone: [
      { required: true, message: '请输入联系电话' }
    ],
    email: [
      { required: true, message: '请输入邮箱' }
    ],
    hireDate: [
      { required: true, message: '请输入聘用日期' }
    ],
    departmentName: [
      { required: true, message: '请输入部门名称' }
    ],
    positionName: [
      { required: true, message: '请输入岗位名称' }
    ],
  };

  let employeeForm: Partial<Employee> = {}

  const [title, setTitle] = useState('新增员工基本信息');

  const provinceCityAreaOptions: AreaOption[] = areas.provinces

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑员工基本信息')
      initEmployeeFormById(id)
    } else {
      setTitle('新增员工基本信息')
      form.resetFields();
    }
  }, [visible]);

  const initEmployeeFormById = async (id: number) => {
    const resp: Result<Employee> = await employeeApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      employeeForm = resp.data
      const provinceCityArea2 = []
      if (employeeForm.province) {
        provinceCityArea2.push(employeeForm.province)
      }
      if (employeeForm.city) {
        provinceCityArea2.push(employeeForm.city)
      }
      if (employeeForm.area) {
        provinceCityArea2.push(employeeForm.area)
      }
      form.setFieldsValue({...employeeForm, provinceCityArea: provinceCityArea2});
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let employee2Save:Employee = form.getFieldsValue()
      if (id) {
        employee2Save = Object.assign(employeeForm, employee2Save)
      }
      const resp: Result<void> = await employeeApi.save(employee2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增员工基本信息')
    form.resetFields();
  };
  
  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [departmentSelectorVisible, setDepartmentSelectorVisible] = useState(false);
  const findDepartment = () => {
    setDepartmentSelectorVisible(true);
  }
  const handleDepartmentSelected = (selectedDepartment: { departmentId?: number; departmentName?: string; }) => {
    setDepartmentSelectorVisible(false)
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      departmentId: selectedDepartment['departmentId'],
      departmentName: selectedDepartment['departmentName'],
      }));
    }
  };
  const handleCloseDepartmentSelector = () => {
    setDepartmentSelectorVisible(false)
  };
  const [positionSelectorVisible, setPositionSelectorVisible] = useState(false);
  const findPosition = () => {
    setPositionSelectorVisible(true);
  }
  const handlePositionSelected = (selectedPosition: { positionId?: number; positionName?: string; }) => {
    setPositionSelectorVisible(false)
    if (selectedPosition && 'positionId' in selectedPosition) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      positionId: selectedPosition['positionId'],
      positionName: selectedPosition['positionName'],
      }));
    }
  };
  const handleClosePositionSelector = () => {
    setPositionSelectorVisible(false)
  };

  const onBack = () => {
    onCloseEmployeeAdd()
  };

  const onAreaChange: CascaderProps<AreaOption>['onChange'] = (value) => {
    if (value && value.length > 0 && typeof value[0] === 'string') {
      employeeForm.province = value[0]
    }
    if (value && value.length > 1 && typeof value[1] === 'string') {
      employeeForm.city = value[1]
    }
    if (value && value.length > 2 && typeof value[2] === 'string') {
      employeeForm.area = value[2]
    }
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseEmployeeAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="employeeForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="enterpriseName" label="企业名称"  rules={rules.enterpriseName}>
              <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="employeeNumber" label="工号" rules={rules.employeeNumber}>
              <Input maxLength={32} placeholder="请输入工号"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="name" label="姓名" rules={rules.name}>
              <Input maxLength={64} placeholder="请输入姓名"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="password" label="密码" rules={rules.password}>
              <Input maxLength={255} placeholder="请输入密码"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="gender" label="性别" rules={rules.gender}>
              <Select placeholder="请选择性别" options={[
                { value: 1, label: <span>男</span> },
                { value: 2, label: <span>女</span> }
              ]} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="birthDate" label="出生日期" rules={rules.birthDate}>
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="contactPhone" label="联系电话" rules={rules.contactPhone}>
              <Input maxLength={64} placeholder="请输入联系电话"/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="email" label="邮箱" rules={rules.email}>
              <Input maxLength={64} placeholder="请输入邮箱"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="provinceCityArea" label="省/市/区">
              <Cascader options={provinceCityAreaOptions} fieldNames={{ label: "name", value: "code" }} onChange={onAreaChange} placeholder="请选择省/市/区" />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="address" label="家庭地址">
              <Input maxLength={255} placeholder="请输入家庭地址"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="hireDate" label="聘用日期" rules={rules.hireDate}>
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="departmentName" label="部门名称"  rules={rules.departmentName}>
              <Input.Search placeholder="请选择部门名称" onSearch={findDepartment} readOnly={true} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="positionName" label="岗位名称"  rules={rules.positionName}>
              <Input.Search placeholder="请选择岗位名称" onSearch={findPosition} readOnly={true} />
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <DepartmentSelector visible={departmentSelectorVisible} onDepartmentSelected={handleDepartmentSelected} onCloseDepartmentSelector={handleCloseDepartmentSelector} />
      <PositionSelector visible={positionSelectorVisible} onPositionSelected={handlePositionSelected} onClosePositionSelector={handleClosePositionSelector} />
    </Modal>
  )
}

export default EmployeeAdd;
